package org.aaron.demos.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadHelper {
	private URL url = null;

	/**
	 * 下载文本类型文件
	 * @param urlStr
	 * @return
	 */
	public String downloadFile2String(String urlStr) {
		StringBuffer buffer = new StringBuffer();
		InputStream inputStream = null;
		BufferedReader bufferedReader = null;
		String line = null;
		try {
			inputStream = getInputStream2Url(urlStr);
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				while ((line = bufferedReader.readLine()) != null) {
					buffer.append(line);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return buffer.toString();
	}
	/**
	 * 下载文件存储在sd卡
	 * @param urlStr 下载地址
	 * @param path	存储目录
	 * @param filename 存储文件名
	 * @return
	 */
	public int downloadFile2Sd(String urlStr,String path,String filename){
		FileUtils fileUtils=new FileUtils();
		InputStream inputStream=null;
		if(FileUtils.RESULT_FILE_IS_EXIST==fileUtils.IsExist2SdFile(path+filename)){
			return FileUtils.RESULT_FILE_IS_EXIST;
		}else{
			try {
				inputStream=getInputStream2Url(urlStr);
				return fileUtils.write2SdFromInput(path, filename, inputStream);
			} catch (IOException e) {
				e.printStackTrace();
				return FileUtils.RESULT_FAIL;
			}
		}
	}
	private InputStream getInputStream2Url(String urlStr) throws IOException {
		InputStream inputStream = null;
		try {
			url = new URL(urlStr);
			URLConnection connection = url.openConnection();
			inputStream = connection.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return inputStream;
	}
}
